<!--
 * @Author: wangshuguang
 * @Date: 2022-02-17 16:29:20
 * @LastEditTime: 2022-03-22 15:10:10
 * @LastEditors: wangshuguang
 * @Description: 文件描述...
-->
<template>
  <div class="infoConfig">
    <el-form :v-model="form" label-width="100px">
      <el-form-item label="支付金额">
        <el-select v-model="form.payMoney" placeholder="请选择" value-key="rechargeFixMoney" size="small" class="width100">
          <el-option
            v-for="item in payList"
            :key="item.value"
            :label="item.label"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式">
        <el-select v-model="form.payType" placeholder="请选择" size="small" class="width100">
          <!-- <el-option label="微信支付" value="WX" /> -->
          <el-option label="支付宝支付" value="ZFB" />
          <el-option :label="`钱包余额（剩余￥${wallNum}）`" value="WALL" />
        </el-select>
      </el-form-item>
      <div class="btnList textCenter">
        <el-button size="small" @click="$emit('close')">取消</el-button>
        <el-button type="primary" size="small" @click="toPay">提交</el-button>
      </div>
    </el-form>

    <el-dialog
      title="支付"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      append-to-body
      width="30%"
      custom-class="infoConfigDialog"
    >
      <!-- 支付中 -->
      <div v-if="!payResult.payStatus">
        <div v-if="form.payType == 'WALL'">
          <el-form :v-model="form" label-width="100px">
            <el-form-item label="支付金额">
              ￥{{ form.payMoney.rechargeFixMoney }}元
            </el-form-item>
            <el-form-item label="购买流量余额">{{ form.payMoney.flowBalance }}</el-form-item>
            <el-form-item label="支付方式">钱包余额</el-form-item>
            <el-form-item label="支付密码">
              <pwd @getPwd="getPwd" />
            </el-form-item>
          </el-form>
        </div>
        <div v-else>
          <div>支付结果查询中。。。</div>
        </div>
      </div>
      <!-- 支付结果展示 -->
      <el-form v-else :v-model="form" label-width="100px">
        <div class="statusHead">
          <div class="imgIcon">
            <i :class="payResult.payStatus == 'S' ? 'el-icon-success' : 'el-icon-error'" />
          </div>
          {{ payResult.payStatus == "S" ? '支付成功' : '支付失败' }}
        </div>
        <el-form-item v-show="payResult.payStatus == 'F'" label="失败原因">{{ payResult.failRemark }}</el-form-item>
        <el-form-item label="支付金额">￥{{ form.payMoney.rechargeFixMoney }}元</el-form-item>
        <el-form-item label="购买流量余额">{{ form.payMoney.flowBalance }}</el-form-item>
        <el-form-item label="支付方式">{{ payType[form.payType] }}</el-form-item>
        <el-form-item label="支付单号">{{ payResult.payTranNo }}</el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <div v-if="form.payType == 'ZFB'">
          <el-button type="primary" @click="payClose">确 定</el-button>
        </div>
        <div v-else-if="!payResult.payStatus">
          <el-button @click="dialogVisible = false">取消支付</el-button>
          <el-button type="primary" @click="paySubmit">确认支付</el-button>
        </div>
        <div v-else>
          <el-button type="primary" @click="payClose">确 定</el-button>
        </div>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import pwd from './pwd.vue'
import {
  agtGetPackageInfo,
  agtGetWallBalance,
  agentPay,
  queryPcAliStatus,
  checkUpFlowBalance
} from '@/api/sp/flow'
import { mapGetters } from 'vuex'
import { dateFtt } from '@/utils'
export default {
  components: { pwd },
  props: {
    infoConfig: {}
  },
  data() {
    return {
      dateFtt,
      payList: [],
      wallNum: 0,
      dialogVisible: false,
      payResult: {},
      dialogData: {},
      payType: {
        'ZFB': '支付宝',
        'WALL': '钱包余额'
      },
      form: {
        pwd: '',
        payMoney: {}
      },
      qrcodeUrl: '',
      value: '',
      payTimer: null,
      payTimerNum: 0
    }
  },
  computed: {
    ...mapGetters(['agentFlow', 'userInfo', 'spInfo']),
    baseData() { return this.infoConfig.data },
    pageType() { return this.infoConfig.type }
  },
  mounted() {
    agtGetPackageInfo({
      agentLv: this.agentFlow.agentLv,
      orgId: this.spInfo.deptId
    }).then(res => {
      console.log('res', res)
      this.payList = res.data.map(item => {
        return {
          ...item,
          label: `${item.rechargeFixMoney}元（可获得流量余额${item.flowBalance}）`
        }
      })
    })
    agtGetWallBalance({
      serial: this.spInfo.syncTmpServicerId
    }).then(res => {
      console.log('res', res)
      this.wallNum = res.data
    })
  },
  methods: {
    handleClose(done) {
      clearTimeout(this.payTimer)
      if (this.payResult.payStatus) {
        // 支付之后 刷新余额并关闭页面
        this.payClose()
        done()
      } else {
        done()
      }
    },
    toPay() {
      if (!this.form.payMoney || !this.form.payMoney.rechargeFixMoney) {
        this.$message.error('请选择支付金额')
        return
      } else if (!this.form.payType) {
        this.$message.error('请选择支付方式')
        return
      } else {
        checkUpFlowBalance({
          payFlowBalance: this.form.payMoney.flowBalance,
          payType: this.form.payType,
          payee: this.spInfo.syncTmpServicerId
        }).then(res => {
          this.payFun(res.data)
        })
      }
    },
    payFun(checkData) {
      if (this.form.payType == 'ZFB') {
        // 支付宝支付
        const obj = {
          'upUserId': checkData.upUserId,
          'upUserRole': checkData.upUserRole,
          comboTotalCost: this.form.payMoney.rechargeFixMoney,
          'deptId': this.spInfo.deptId,
          payFlowBalance: this.form.payMoney.flowBalance,
          payType: this.form.payType,
          'payee': this.spInfo.syncTmpServicerId,
          'payerRoleType': this.spInfo.roleAlias,
          subject: '充值流量余额',
          totalAmount: this.form.payMoney.rechargeFixMoney
        }
        const { href } = this.$router.resolve({
          name: 'zfbPay',
          query: obj
        })
        window.open(href, '_blank')
        // 轮训接口 查询支付状态
        this.$confirm('是否已经完成支付?', '提示', {
          confirmButtonText: '我已支付',
          cancelButtonText: '未支付',
          type: 'warning'
        }).then(() => {
          // 轮训查询支付状态
          this.queryPayStatus()
          this.dialogVisible = true
        }).catch(() => {
          this.payClose()
        })
      } else {
        this.dialogVisible = true
      }
    },
    // 查询支付宝支付状态
    queryPayStatus() {
      const businessNo = localStorage.getItem('zfbPayBusinessNo')
      queryPcAliStatus({
        businessNo,
        payFlowBalance: this.form.payMoney.flowBalance
      }).then(res => {
        console.log('then', res)
        this.payResult = { ...res.data }
      }).catch(res => {
        console.log('catch', res)
        // 未查询到结果  继续轮训
        console.log('setTimeout', 1)

        // 超过6次终止轮训
        if (this.payTimerNum == 6) {
          this.$toast('网络忙，清稍后再试')
          this.loading = false
        } else {
          this.payTimerNum++
          this.getOrdetTimer = setTimeout(() => {
            this.queryPayStatus()
          }, 10 * 1000)
        }
      })
    },
    payClose() {
      this.payResult = {}
      this.dialogVisible = false
      this.$emit('sucClose')
    },
    paySubmit() {
      const { pwd, payType, payMoney } = this.form
      const obj = {
        'agentId': this.spInfo.syncTmpServicerId,
        'deptId': this.spInfo.payMerchantNo,
        'flowBalance': payMoney.flowBalance,
        'operation': '9',
        'payAmount': payMoney.rechargeFixMoney,
        'payPassword': pwd,
        'payType': payType,
        'remark': '',
        'userType': 'agent'
      }
      console.log('agentPay', obj)
      agentPay(obj).then(res => {
        console.log('res', res)
        this.payResult = res.data
      })
    },
    getPwd(data) {
      console.log('getPwd', data)
      this.form.pwd = data
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.infoConfig{
  padding: 20px;
}
.infoConfigDialog{
  .statusHead{
    text-align: center;
    font-size: 20px;
    .imgIcon{
      font-size: 50px;
      .el-icon-success{
        color: #19D5AE;
      }
      .el-icon-error{
        color: #FD0000;
      }
    }
  }
}
</style>
